package org.example;
import org.eclipse.paho.client.mqttv3.*;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake. ServerHandshake;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.net.URI;
import java. net.URISyntaxException;

public class WebSocketMqttClient {
    public static void main(String[] args) {
        String broker = "tcp://192.168.31.115:1883";
        String clientId = "emqx_001";
        String topic = "topic2";
        try {
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName("emqx_01");
            options.setPassword("123456".toCharArray());
            client.connect(options);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost: " + cause.getMessage());
                }
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Received message: " + new String(message.getPayload()));
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // Not used in this example
                }
            });
            client.subscribe(topic);
            String message = "Hello, MQTT!";
            client.publish(topic, new MqttMessage(message.getBytes()));
            Thread.sleep(5000); // 等待接收消息
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}